<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form name="f1" onsubmit="validate()">
        姓名：
        <input type="text" name="username" id="username_id">
        <br> 性别：
        <select name="opt" id="gender">
            <option value="0">请选择性别</option>
            <option value="1">male</option>
            <option value="2">female</option>
        </select>
        <br>
        <br>
        <input type="submit" value="提交">
        <input type="reset" value="重置">
        <button onclick="doClick()">button</button>
    </form>

    <script>
        function validate() {
            // 1.可以通过document.getElementById获取input元素
            // alert(document.getElementById("username_id").value);
            // 2.通过document取到整个表单form，再取form里面的表单元素（根据name或者id属性值）
            var name = document.f1.username_id.value;
            alert(name);
            var gender = document.f1.opt.value;
            if (name == "" || gender == "0") {
                alert("请选择性别或请输入姓名");
            }
        }
    </script>
</body>

</html>